<?php

namespace app\common\model\product;

use app\common\model\proxy\User;
use think\facade\Cache;
use app\common\model\BaseModel;

/**
 * 产品分类模型
 */
class Category extends BaseModel
{
    protected $pk = 'category_id';
    protected $name = 'category';

    /**
     * 分类图片
     */
    public function images()
    {
        return $this->hasOne('app\\common\\model\\file\\UploadFile', 'file_id', 'image_id');
    }

    /**
     * 代理
     * @return \think\model\relation\BelongsTo
     * @Author joey
     * @date 2024/3/29 15:22
     */
    public function proxy()
    {
        return $this->belongsTo(User::class, 'proxy_id', 'proxy_id');
    }

    /**
     * 充值套餐详情
     */
    public static function detail($category_id)
    {
        return (new static())->find($category_id);
    }


    public function detailWithImage($where)
    {
        return $this->with(['image'])->where($where)->find();
    }

    /**
     * 子分类
     * @return \think\model\relation\HasMany
     * @Author joey
     * @date 2024/4/2 14:15
     */
    public function children()
    {
        return $this->hasMany(self::class,'parent_id', 'category_id')->order('sort ASC,create_time DESC')->field('category_id,parent_id,name');
    }
    /**
     * @Exp    所有分类
     * @Author Mr.Z
     * @Date   2024-02-27
     * @param  integer    $newPeple [会员：2全部，1普通会员，0新人]
     * @param  array    $where [会员：2全部，1普通会员，0新人]
     * @return [type]               [description]
     */
    public static function getALL($newPeple=2, $where = [])
    {
        $model = new static;
        $base = ['audit_status' => 1];
        if ($where) {
            $base = array_merge($base, $where);
        }
        $model = $model->where($base);

        if($newPeple==2){
            $data = $model->with(['images', 'proxy' => function ($query) {
                $query->withField('proxy_id, name');
            }])->order(['sort' => 'asc', 'create_time' => 'asc'])->select();
        }elseif($newPeple==1){
            $data = $model->where('type','=','0')->with(['images', 'proxy' => function ($query) {
                $query->withField('proxy_id, name');
            }])->where(['is_show'=>1])->order(['sort' => 'asc', 'create_time' => 'asc'])->select();
        }else{
            $data = $model->with(['images', 'proxy' => function ($query) {
                $query->withField('proxy_id, name');
            }])->where(['is_show'=>1])->order(['type'=>'desc','sort' => 'asc', 'create_time' => 'asc'])->select();
        }
        $all = !empty($data) ? $data->toArray() : [];
        $tree = [];
        foreach ($all as $first) {
            if ($first['parent_id'] != 0) continue;
            $twoTree = [];
            foreach ($all as $two) {
                if ($two['parent_id'] != $first['category_id']) continue;
                $threeTree = [];
                foreach ($all as $three)
                    $three['parent_id'] == $two['category_id']
                    && $threeTree[$three['category_id']] = $three;
                !empty($threeTree) && $two['child'] = $threeTree;
                array_push($twoTree, $two);
            }
            if (!empty($twoTree)) {
                $temp_two_tree = array_column($twoTree, 'sort');
                array_multisort($temp_two_tree, SORT_ASC, $twoTree);
                $first['child'] = $twoTree;
            }
            array_push($tree, $first);
        }

        return compact('all', 'tree');
    }

    /**
     * 获取所有分类
     */
    public static function getCacheAll()
    {
        return self::getALL()['all'];
    }

    /**
     * @Exp    获取所有分类(树状结构)
     * @Author Mr.Z
     * @Date   2024-02-27
     * @param  integer    $newPeple [会员：2全部，1普通会员，0新人]
     * @param  array    $where [会员：2全部，1普通会员，0新人]
     * @return [type]               [description]
     */
    public static function getCacheTree($newPeple=2, $where = [])
    {
        return self::getALL($newPeple, $where)['tree'];
    }

    /**
     * 获取所有分类(树状结构)
     * @return string
     */
    public static function getCacheTreeJson()
    {
        return json_encode(static::getCacheTree());
    }

    /**
     * 获取指定分类下的所有子分类id
     */
    public static function getSubCategoryId($parent_id, $all = [])
    {
        $arrIds = [$parent_id];
        empty($all) && $all = self::getCacheAll();
        foreach ($all as $key => $item) {
            if ($item['parent_id'] == $parent_id) {
                unset($all[$key]);
                $subIds = self::getSubCategoryId($item['category_id'], $all);
                !empty($subIds) && $arrIds = array_merge($arrIds, $subIds);
            }
        }
        return $arrIds;
    }

    /**
     * 指定的分类下是否存在子分类
     */
    protected static function hasSubCategory($parentId)
    {
        $all = self::getCacheAll();
        foreach ($all as $item) {
            if ($item['parent_id'] == $parentId) {
                return true;
            }
        }
        return false;
    }


    /**
     * 关联图片
     */
    public function image()
    {
        return $this->belongsTo('app\common\model\file\UploadFile', 'image_id', 'file_id');
    }

    /**
     * 获取所有一级分类
     */
    public static function getFirstCategory()
    {
        return (new static())->where('parent_id', '=', 0)
            ->order(['sort' => 'asc', 'create_time' => 'asc'])
            ->select();
    }

    public function getListByIds($ids)
    {
        return $this->field(['category_id', 'name', 'parent_id'])->where('category_id', 'in', $ids)->select();
    }

    /**
     * @Exp    输出短类
     * @Date   2024-03-19
     * @param  [type]     $parentId     [description]
     * @param  [type]     $categorylist [description]
     * @return [type]                   [description]
     */
    public static function smallNameList($parentId,$categorylist){
        $outAry = [];
        $skey = 0;
        foreach ($categorylist as $key => $value) {
            if($parentId == $value['category_id']){
                if(isset($value['child'])&&count($value['child'])>0){
                    foreach ($value['child'] as $svalue) {
                        $outAry[$skey] = self::filterFunc($svalue);
                        $skey++;
                    }
                }
            }
        }
        return $outAry;
    }

    /**
     * @Exp    获取父id
     * @param  [type]     $data [description]
     * @return [type]           [description]
     */
    public static function getParentId($data){
        return (new static())->where("category_id", $data["category_id"])
            ->value("parent_id");
    }

    // 定义一个过滤函数
    private static function filterFunc($value) {
        return ['category_id'=>$value['category_id'],'name'=>$value['name'],'parent_id'=>$value['parent_id']];
    }
}
